package com.dpwgc.easywebpay.module.alipay.util;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.dpwgc.easywebpay.base.dao.Order;
import com.dpwgc.easywebpay.base.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class PayUtil {

    @Value("${alipay.appId}")
    String appId;
    @Value("${alipay.api}")
    String api;
    @Value("${alipay.notifyUrl}")
    String notifyUrl;
    @Value("${alipay.returnUrl}")
    String returnUrl;
    @Value("${alipay.aliPublicKey}")
    String aliPublicKey;
    @Value("${alipay.privateKey}")
    String privateKey;
    @Value("${alipay.timeout}")
    Long timeout;

    @Autowired
    DateUtil dateUtil;

    /**
     * 生成网页支付web页面 支付宝文档：https://opendocs.alipay.com/open/028r8t?scene=22
     * @param orderNo 订单号
     * @param price 订单价格
     * @param subject 订单主题
     * @return String
     * @throws AlipayApiException
     */
    public String webPay(String orderNo,double price,String subject) throws AlipayApiException {

        AlipayClient alipayClient = new DefaultAlipayClient(api,appId,privateKey,"json","UTF-8",aliPublicKey,"RSA2");
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

        request.setNotifyUrl(notifyUrl);//支付宝服务器主动通知商户服务器里指定的页面http/https路径。自行设置扩展
        request.setReturnUrl(returnUrl);//回调地址，自行设置扩展

        JSONObject bizContent = new JSONObject();

        /* 如需扩展字段，请自行添加 */

        //基础字段
        bizContent.put("out_trade_no", orderNo);    //订单号
        bizContent.put("total_amount", price);      //交易金额
        bizContent.put("subject", subject);         //订单主题
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        bizContent.put("time_expire", dateUtil.getDateTimeLate(timeout));//设置订单过期日期（在timeout秒后过期）

        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        if(response.isSuccess()){
            return response.getBody();
        }
        return "";
    }

    /**
     * 获取用户订单的支付情况 支付宝文档：https://opendocs.alipay.com/open/028woa
     * @param order 订单
     * @return String
     */
    public String getPayInfo(Order order) {

        try {
            AlipayClient alipayClient = new DefaultAlipayClient(api,appId,privateKey,"json","UTF-8",aliPublicKey,"RSA2");
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", order.getOrderNo());
            //bizContent.put("trade_no", "2014112611001004680073956707");
            request.setBizContent(bizContent.toString());
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                return response.getTradeStatus();   //返回订单状态
            } else {
                //返回错误代码
                return response.getCode();
            }
        }catch (AlipayApiException e){
            return "";
        }
    }
}
